<template>
  <div class="px-4 pb-16">
    <!-- 编辑模式操作栏 -->
    <div v-if="isEditMode" class="flex justify-between items-center mb-4 p-3 bg-gray-800 rounded-lg">
      <div class="flex items-center gap-4">
        <button
          @click="toggleSelectAll"
          class="px-3 py-1 text-orange-400 text-sm border border-orange-400 rounded hover:bg-orange-400 hover:text-white transition-colors flex items-center gap-1"
        >
          <i :class="['fas', isAllSelected ? 'fa-check-square' : 'fa-square']"></i>
          {{ isAllSelected ? '取消全选' : '全选' }}
        </button>
        <span class="text-gray-400 text-sm">已选择 {{ selectedItems.length }} 项</span>
      </div>
      <div class="flex gap-2">
        <button
          @click="deleteSelected"
          :disabled="selectedItems.length === 0"
          class="px-3 py-1 text-white text-sm bg-red-600 rounded hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed"
        >
          删除 ({{ selectedItems.length }})
        </button>
      </div>
    </div>

    <!-- 加载状态 - 替换为骨架屏 -->
    <div v-if="loading" class="grid grid-cols-3 gap-3">
      <div v-for="i in 6" :key="i" class="bg-gray-900 rounded-lg overflow-hidden shadow-sm">
        <div class="skeleton-img-dark"></div>
        <div class="p-2">
          <div class="skeleton-text-short-dark"></div>
          <div class="skeleton-text-mini-dark mt-1"></div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="watchingList.length === 0" class="empty-state">
      <i class="far fa-sad-tear empty-icon"></i>
      <p class="empty-text">您还没有追剧，去首页发现好剧吧</p>
    </div>

    <!-- 剧集列表 -->
    <div v-else class="grid grid-cols-3 gap-3">
      <div
        v-for="drama in watchingList"
        :key="drama.id"
        class="bg-gray-900 rounded-lg overflow-hidden shadow-sm cursor-pointer hover:shadow-md transition-shadow relative"
        @click="handleDramaClick(drama)"
      >
        <!-- 编辑模式复选框 -->
        <div v-if="isEditMode" class="absolute top-2 left-2 z-10" @click.stop="toggleSelection(drama.id)">
          <div class="w-5 h-5 rounded border-2 border-white bg-black bg-opacity-60 flex items-center justify-center">
            <i v-if="selectedItems.includes(drama.id)" class="fas fa-check text-white text-xs"></i>
          </div>
        </div>

        <!-- 封面区域 -->
        <div class="relative">
          <img :src="drama.cover" class="w-full h-32 object-cover" :alt="drama.title" />
          <div class="absolute bottom-2 left-2 text-white text-xs bg-black bg-opacity-60 px-2 py-1 rounded">
            {{ drama.totalEpisodes }}集
          </div>
        </div>

        <!-- 信息区域 -->
        <div class="p-2">
          <h3 class="text-white font-medium mb-1 text-sm truncate">
            {{ drama.title }}
          </h3>
          <p class="text-gray-400 text-xs">追到第{{ drama.currentWatchEpisode }}集</p>
        </div>
      </div>
    </div>

    <!-- Toast提示 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { reqBatchDeleteFollowing, reqFollowingDramas } from '@/apis/video'

// 定义props
const props = defineProps({
  isEditMode: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['exit-edit-mode'])

// 路由实例
const router = useRouter()

// 在追剧集数据
const watchingList = ref([])

// 选中的项目
const selectedItems = ref([])

// 加载状态
const loading = ref(true)

// 提示消息
const toastMessage = ref('')
const showToast = ref(false)

// 显示提示消息
const showToastMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}

// 计算属性：是否全选
const isAllSelected = computed(() => {
  return watchingList.value.length > 0 && selectedItems.value.length === watchingList.value.length
})

// 切换单个项目选择
const toggleSelection = (dramaId) => {
  const index = selectedItems.value.indexOf(dramaId)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(dramaId)
  }
}

// 切换全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedItems.value = []
  } else {
    selectedItems.value = watchingList.value.map((drama) => drama.id)
  }
}

// 取消选择
const cancelSelection = () => {
  selectedItems.value = []
  emit('exit-edit-mode')
}

// 删除选中项
const deleteSelected = async () => {
  if (selectedItems.value.length === 0) return

  try {
    const result = await showConfirmDialog({
      title: '提示',
      message: `确定要删除选中的 ${selectedItems.value.length} 个追剧吗？`
    })

    console.log('开始删除选中项:', selectedItems.value)
    console.log('选中项类型:', typeof selectedItems.value[0], '数组长度:', selectedItems.value.length)

    // 确保传递的是有效的ID数组
    const dramaIds = selectedItems.value.map((id) => Number(id)).filter((id) => !isNaN(id) && id > 0)

    if (dramaIds.length === 0) {
      showToastMessage('没有有效的剧集可以删除')
      return
    }

    console.log('转换后的ID数组:', dramaIds)

    // 显示加载状态
    showToastMessage('正在删除...')

    try {
      // 调用批量删除API
      const response = await reqBatchDeleteFollowing(dramaIds)
      console.log('删除API响应:', response)

      // 检查响应格式
      if (!response || typeof response !== 'object') {
        throw new Error('服务器响应格式异常')
      }

      // 检查响应状态
      if (response.code !== 200) {
        throw new Error(response.message || '删除失败')
      }

      // API调用成功后，从本地数组中移除成功删除的项目
      const successIds = response.data?.successIds || dramaIds
      if (successIds.length > 0) {
        watchingList.value = watchingList.value.filter((drama) => !successIds.includes(drama.id))
      }

      // 清空选中项并退出编辑模式
      selectedItems.value = []
      emit('exit-edit-mode')

      // 显示删除结果
      const { successCount = 0, failedCount = 0 } = response.data || {}
      if (failedCount > 0) {
        showToastMessage(`删除完成：成功 ${successCount} 个，失败 ${failedCount} 个`)
      } else {
        showToastMessage(`成功删除 ${successCount} 个追剧`)
      }
    } catch (apiError) {
      throw apiError
    }
  } catch (error) {
    console.error('删除操作失败:', error)

    // 根据错误类型显示不同的提示
    let errorMessage = '删除失败，请重试'

    if (error.message) {
      if (error.message.includes('网络') || error.message.includes('timeout')) {
        errorMessage = '网络连接失败，请检查网络后重试'
      } else if (error.message.includes('无效') || error.message.includes('格式')) {
        errorMessage = '选中的剧集数据异常，请刷新页面后重试'
      } else if (error.message.includes('权限') || error.message.includes('401')) {
        errorMessage = '登录已过期，请重新登录'
      } else {
        errorMessage = error.message
      }
    }

    showToastMessage(errorMessage)
  }
}

// 监听编辑模式变化，重置选择状态
watch(
  () => props.isEditMode,
  (newVal) => {
    if (!newVal) {
      selectedItems.value = []
    }
  }
)

// 处理剧集点击
const handleDramaClick = (drama) => {
  // 编辑模式下点击切换选择状态
  if (props.isEditMode) {
    toggleSelection(drama.id)
    return
  }

  // 如果剧集有videos数据，直接传递
  if (drama.videos && drama.videos.length > 0) {
    console.log('跳转到播放页面', drama.videos)

    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  } else {
    // 否则只传递dramaId和episodeIndex，让播放页面自己获取数据
    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  }
}

// 获取在追剧集数据
const getFollowingDramas = async () => {
  try {
    loading.value = true
    const response = await reqFollowingDramas()
    console.log('在追剧集数据:', response)
    const { list, pagination } = response.data
    watchingList.value = list || []
  } catch (error) {
    console.error('❌ 获取在追剧集失败:', error)
    showToastMessage('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getFollowingDramas()
})
</script>

<style scoped>
/* 文本截断 */
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 防止按钮点击事件冒泡 */
button {
  user-select: none;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  height: 30vh;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  border-top-color: #f97316;
  border-radius: 50%;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

.loading-text {
  color: #d1d5db;
  font-size: 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 空数据状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  color: #9ca3af;
  height: 30vh;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #6b7280;
}

.empty-text {
  font-size: 1rem;
  color: #9ca3af;
}

/* Toast提示样式 */
.toast-message {
  position: fixed;
  bottom: 5rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  z-index: 50;
}

/* 骨架屏样式 - 深色主题 */
.skeleton-img-dark {
  height: 128px;
  width: 100%;
  background: linear-gradient(110deg, #2a2a2a 30%, #3a3a3a 50%, #2a2a2a 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-short-dark {
  height: 16px;
  width: 80%;
  border-radius: 4px;
  background: linear-gradient(110deg, #2a2a2a 30%, #3a3a3a 50%, #2a2a2a 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-mini-dark {
  height: 12px;
  width: 50%;
  border-radius: 4px;
  background: linear-gradient(110deg, #2a2a2a 30%, #3a3a3a 50%, #2a2a2a 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 优化移动端体验 */
@media (max-width: 640px) {
  .grid-cols-3 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

/* 行裁剪样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
